package com.gusti.turnos.servlet.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author gusti
 *
 */
public class ExceptionFilter implements Filter {

	private FilterConfig filterConfig;

	public void init( FilterConfig filterConfig ) {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws ServletException, IOException {

		if ( filterConfig == null) {
			return;
		}

		HttpServletResponse httpResponse = (HttpServletResponse) response;

		try {
			// Invoke the next filter in the chain
			chain.doFilter( request, response );
		} catch( Exception e ) {
//			httpResponse.sendError( HttpServletResponse.SC_OK, e.getCause().getLocalizedMessage() );
//			httpResponse.sendRedirect( url ) ;
			httpResponse.setCharacterEncoding( "UTF-8" );
			httpResponse.setContentType( "text/plain" );
			httpResponse.setStatus( HttpServletResponse.SC_OK );

			try {
				PrintWriter printWriter = httpResponse.getWriter();
				printWriter.println( e.getCause().getLocalizedMessage() );
			} catch (Exception ex) {
				//this happens cause rest
				//nothing else matters
			}
		}
	}
}
